"""
RedFire Framework - 应用生命周期管理模块

提供应用启动、关闭的生命周期管理功能，确保所有组件的正确初始化和清理。
"""

import asyncio
import logging
from typing import List, Callable, Any, Optional
from abc import ABC, abstractmethod
from contextlib import asynccontextmanager

logger = logging.getLogger(__name__)


class ILifecycleHook(ABC):
    """生命周期钩子接口"""
    
    @abstractmethod
    async def on_startup(self) -> None:
        """应用启动时执行"""
        pass
    
    @abstractmethod
    async def on_shutdown(self) -> None:
        """应用关闭时执行"""
        pass
    
    @property
    @abstractmethod
    def name(self) -> str:
        """钩子名称"""
        pass
    
    @property
    def priority(self) -> int:
        """执行优先级，数值越小优先级越高"""
        return 100


class DatabaseLifecycleHook(ILifecycleHook):
    """数据库连接生命周期钩子"""
    
    def __init__(self, database_factory=None):
        self.database_factory = database_factory
    
    async def on_startup(self) -> None:
        """初始化数据库连接"""
        logger.info("正在初始化数据库连接...")
        if self.database_factory:
            await self.database_factory.initialize()
        logger.info("数据库连接初始化完成")
    
    async def on_shutdown(self) -> None:
        """关闭数据库连接"""
        logger.info("正在关闭数据库连接...")
        if self.database_factory:
            await self.database_factory.close_all()
        logger.info("数据库连接已关闭")
    
    @property
    def name(self) -> str:
        return "database"
    
    @property
    def priority(self) -> int:
        return 10  # 高优先级，最先启动，最后关闭


class CacheLifecycleHook(ILifecycleHook):
    """缓存连接生命周期钩子"""
    
    def __init__(self, cache_manager=None):
        self.cache_manager = cache_manager
    
    async def on_startup(self) -> None:
        """初始化缓存连接"""
        logger.info("正在初始化缓存连接...")
        if self.cache_manager:
            await self.cache_manager.initialize()
        logger.info("缓存连接初始化完成")
    
    async def on_shutdown(self) -> None:
        """关闭缓存连接"""
        logger.info("正在关闭缓存连接...")
        if self.cache_manager:
            await self.cache_manager.close()
        logger.info("缓存连接已关闭")
    
    @property
    def name(self) -> str:
        return "cache"
    
    @property
    def priority(self) -> int:
        return 20


class EventBusLifecycleHook(ILifecycleHook):
    """事件总线生命周期钩子"""
    
    def __init__(self, event_bus=None):
        self.event_bus = event_bus
    
    async def on_startup(self) -> None:
        """启动事件总线"""
        logger.info("正在启动事件总线...")
        if self.event_bus:
            await self.event_bus.start()
        logger.info("事件总线启动完成")
    
    async def on_shutdown(self) -> None:
        """停止事件总线"""
        logger.info("正在停止事件总线...")
        if self.event_bus:
            await self.event_bus.stop()
        logger.info("事件总线已停止")
    
    @property
    def name(self) -> str:
        return "event_bus"
    
    @property
    def priority(self) -> int:
        return 30


class ApplicationLifecycleManager:
    """应用生命周期管理器
    
    负责管理应用的启动和关闭过程，确保所有组件按正确顺序初始化和清理。
    """
    
    def __init__(self):
        self.startup_hooks: List[ILifecycleHook] = []
        self.shutdown_hooks: List[ILifecycleHook] = []
        self.custom_startup_handlers: List[Callable] = []
        self.custom_shutdown_handlers: List[Callable] = []
        self._is_started = False
    
    def add_hook(self, hook: ILifecycleHook) -> None:
        """添加生命周期钩子"""
        self.startup_hooks.append(hook)
        self.shutdown_hooks.append(hook)
        
        # 按优先级排序
        self.startup_hooks.sort(key=lambda x: x.priority)
        # 关闭时逆序执行
        self.shutdown_hooks.sort(key=lambda x: x.priority, reverse=True)
    
    def add_startup_handler(self, handler: Callable) -> None:
        """添加自定义启动处理器"""
        self.custom_startup_handlers.append(handler)
    
    def add_shutdown_handler(self, handler: Callable) -> None:
        """添加自定义关闭处理器"""
        self.custom_shutdown_handlers.append(handler)
    
    async def startup(self) -> None:
        """执行应用启动序列"""
        if self._is_started:
            logger.warning("应用已经启动，跳过重复启动")
            return
        
        logger.info("开始应用启动序列...")
        
        try:
            # 执行钩子的启动方法
            for hook in self.startup_hooks:
                logger.debug(f"执行启动钩子: {hook.name}")
                await hook.on_startup()
            
            # 执行自定义启动处理器
            for handler in self.custom_startup_handlers:
                logger.debug(f"执行自定义启动处理器: {handler.__name__}")
                if asyncio.iscoroutinefunction(handler):
                    await handler()
                else:
                    handler()
            
            self._is_started = True
            logger.info("应用启动序列完成")
            
        except Exception as e:
            logger.error(f"应用启动失败: {e}")
            # 如果启动失败，尝试清理已初始化的资源
            await self._emergency_cleanup()
            raise
    
    async def shutdown(self) -> None:
        """执行应用关闭序列"""
        if not self._is_started:
            logger.warning("应用未启动，跳过关闭序列")
            return
        
        logger.info("开始应用关闭序列...")
        
        try:
            # 执行自定义关闭处理器
            for handler in reversed(self.custom_shutdown_handlers):
                try:
                    logger.debug(f"执行自定义关闭处理器: {handler.__name__}")
                    if asyncio.iscoroutinefunction(handler):
                        await handler()
                    else:
                        handler()
                except Exception as e:
                    logger.error(f"自定义关闭处理器执行失败: {e}")
            
            # 执行钩子的关闭方法
            for hook in self.shutdown_hooks:
                try:
                    logger.debug(f"执行关闭钩子: {hook.name}")
                    await hook.on_shutdown()
                except Exception as e:
                    logger.error(f"关闭钩子 {hook.name} 执行失败: {e}")
            
            self._is_started = False
            logger.info("应用关闭序列完成")
            
        except Exception as e:
            logger.error(f"应用关闭失败: {e}")
            raise
    
    async def _emergency_cleanup(self) -> None:
        """紧急清理，当启动失败时调用"""
        logger.warning("执行紧急清理...")
        
        for hook in self.shutdown_hooks:
            try:
                await hook.on_shutdown()
            except Exception as e:
                logger.error(f"紧急清理钩子 {hook.name} 失败: {e}")
    
    @asynccontextmanager
    async def lifespan(self, app):
        """FastAPI lifespan context manager"""
        try:
            await self.startup()
            yield
        finally:
            await self.shutdown()
    
    def is_started(self) -> bool:
        """检查应用是否已启动"""
        return self._is_started


# 全局实例和装饰器已废弃，生命周期管理应由应用主程序或DI容器负责
# lifecycle_manager = ApplicationLifecycleManager()
# def startup_handler(...)
# def shutdown_handler(...)
# def get_lifecycle_manager(...)